<template>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: 'homepage' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 警告区域 -->
        <el-alert show-icon title="注意：值允许为第三级分类设置相关参数" type="warning" :closable="false" />
        <!-- 选择商品区域 -->
        <el-row>
            <el-col>
                <span>选择商品分类：</span>
                <!-- 级联选择器 -->
                <el-cascader v-model="selestKeys" :options="paralist" :props="cascaderProps" @change="handleChange"
                    placeholder="请选择" ref="cascaderRef" style="width: 28%;">
                </el-cascader>
            </el-col>
        </el-row>
        <!-- 标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 动态标签 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="isBtnDisabled" @click="paraDialog = true">添加参数</el-button>
                <el-table :data="mantTabData" style="width: 100%;margin-top: 15px;" border stripe row-key="attr_id"
                    :expand-row-keys="expandedRowKeys">
                    <!-- 展开行 -->
                    <el-table-column type="expand" class="table-cloumn">
                        <template #default="scope">
                            <!-- 渲染tag标签 -->
                            <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index.id"
                                @close="handleClose(index, scope.row)">
                                {{ item }}
                            </el-tag>
                            <!-- 输入的文本 -->
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                ref="InputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)" @keydown.stop @click.stop>
                            </el-input>
                            <!-- 添加按钮 -->
                            <el-button v-else class="button-new-tag" size="small" @click.stop="showInput(scope.row)">
                                + NewTag
                            </el-button>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index" label="#"/>
                    <el-table-column prop="attr_name" label="参数名称" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" type="primary" icon="edit"
                                @click="handleEdit(scope.row.attr_id)">编辑</el-button>
                            <el-button size="small" type="danger" icon="delete"
                                @click="ParaDelete(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <!-- 静态标签 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" :disabled="isBtnDisabled" @click="paraDialog = true">添加属性</el-button>
                <el-table :data="onlyTabData" style="width: 100%;margin-top: 15px;" border stripe row-key="attr_id"
                    :expand-row-keys="expandedRowKeys">
                    <!-- 展开行 -->
                    <el-table-column type="expand" class="table-cloumn">
                        <template #default="scope">
                            <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index.id"
                                @close="handleClose(index, scope.row)">
                                {{ item }}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                ref="InputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)" @keydown.stop @click.stop>
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click.stop="showInput(scope.row)">
                                + New Tag
                            </el-button>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index" />
                    <el-table-column prop="attr_name" label="属性名称" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" type="primary" icon="edit"
                                @click="handleEdit(scope.row.attr_id)">编辑</el-button>
                            <el-button size="small" type="danger" icon="delete"
                                @click="ParaDelete(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog v-model="paraDialog" :title="'添加' + titleText" width="450" @close="CateClose()">
        <el-form :model="parafrom" :rules="addparaRules" ref="parafromRef">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="parafrom.attr_name" />
            </el-form-item>
        </el-form>
        <template #footer="">
            <div class="dialog-footer">
                <el-button @click="paraDialog = false">取 消</el-button>
                <el-button type="primary" @click="addpara()">确 定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 编辑按钮对话框 -->
    <el-dialog v-model="editDialog" :title="'修改' + titleText" width="450" @close="paraClose()">
        <el-form :model="patalist" :rules="addparaRules" ref="addparafromRrf">
            <el-form-item :label="titleText" prop="attr_name">
                <el-input v-model="patalist.attr_name" />
            </el-form-item>
        </el-form>
        <template #footer="">
            <div class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="addpara_two(this.editingId)">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import { ElMessage } from 'element-plus';
export default {
    props: [],
    data() {
        return {
            paralist: [],     //商品分类数据
            selestKeys: [],         //级联选择框双向绑定到的数据
            cascaderProps: {    //指定级联选择器的配置对象
                value: 'cat_id',     //指定选项的值为选项对象的某个属性值
                label: 'cat_name',   //指定选项标签为选项对象的某个属性值
                children: 'children',   //指定选项的子选项为选项对象的某个属性值
                expandTrigger: 'hover',
            },
            parafrom: {         //添加动态参数的数据
                attr_name: '',
            },
            patalist: {},           //  编辑按钮获取的数据

            editingId: '',    //当前行参数id
            addparaRules: {     //校验规则
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ]
            },
            activeName: 'many',     //默认选中的标签页
            mantTabData: [],          //动态参数的数据
            onlyTabData: [],          //静态属性的数据
            paraDialog: false,       //控制添加动态对话框
            editDialog: false,       //控制编辑按钮对话框
            expandedRowKeys: [],       // 记录展开的行，防止输入时折叠
        }
    },
    methods: {
        // 获取商品分类数据
        async getparaList() {
            const res = await this.$axios.get("categories")
            // console.log(res);
            this.paralist = res.data.data;
        },
        //父级分类框中选中发生的数据
        handleChange() {
            // console.log(this.selestKeys);
            this.getParamsData();
        },
        //tab标签页点击触发的事件
        handleTabClick(item) {
            // console.log(item)
            this.activeName = item.props.name;
            // console.log(this.activeName);
            this.getParamsData()
        },
        //获取参数列表的数据
        async getParamsData() {
            const res = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: '获取成功',
                    type: 'success'
                })
                res.data.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                    //显示文本框的显示与隐藏
                    item.inputVisible = false;
                    //文本框的输入内容
                    item.inputValue = ''
                });
                // console.log(res.data.data);
                if (this.activeName === 'many') {
                    this.mantTabData = res.data.data;
                } else {
                    this.onlyTabData = res.data.data
                }
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //清空动态参数对话框
        CateClose() {
            this.$refs.parafromRef.resetFields()
        },
        //清空编辑对话框
        paraClose() {
            this.$refs.addparafromRrf.resetFields()
        },
        //确认动态参数对话框
        addpara() {
            this.$refs.parafromRef.validate(async valid => {           //验证表单通过才能提交
                if (!valid) return
                const res = await this.$axios.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.parafrom.attr_name,
                    attr_sel: this.activeName
                })
                // console.log(res);
                if (res.data.meta.status == 201) {
                    ElMessage({
                        message: '创建成功',
                        type: 'success'
                    })
                    this.getParamsData()
                    this.paraDialog = false
                } else {
                    ElMessage.error(res.data.meta.msg)
                }
            })

        },
        //编辑按钮获取数据
        async handleEdit(id) {
            this.editingId = id;
            this.editDialog = true;
            const res = await this.$axios.get(`categories/${this.cateId}/attributes/${id}`, { attr_sel: this.activeName })
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: '获取成功',
                    type: 'success'
                })
                // console.log(res);
                this.patalist = res.data.data
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //编辑按钮确认
        async addpara_two(id) {
            const res = await this.$axios.put(`categories/${this.cateId}/attributes/${id}`, {
                attr_name: this.patalist.attr_name,
                attr_sel: this.activeName
            })
            if (res.data.meta.status == 200) {
                ElMessage({
                    message: '更新成功',
                    type: 'success'
                })
                // console.log(res);
                this.editDialog = false;
                this.getParamsData()
            } else {
                ElMessage.error(res.data.meta.msg)
            }
        },
        //删除按钮
        async ParaDelete(id) {
            try {
                await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                const res = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`);
                // console.log(res);
                if (res.data.meta.status == 200) {
                    this.getParamsData();
                    this.$message({
                        message: "删除成功",
                        type: 'success'
                    })
                } else {
                    this.$message.error(res.meta.msg)
                }
            } catch (error) {
                if (error === 'cancel') {
                    this.$message.info('已取消删除')
                } else {
                    this.$message.error('删除失败')
                }
            }
        },
        //tag标签失去焦点或  按下enter触发
        async handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            } else {
                // 如果没有return ，则证明输入了内容
                row.attr_vals.push(row.inputValue.trim())
                row.inputValue = ''
                row.inputVisible = false

                // 发起请求保存
                this.saveAttrVals(row)
            }
        },
        async saveAttrVals(row) {
            let data = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            })
            if (data.data.meta.status !== 200) {
                return this.$message.error("修改参数项失败")
            } else {
                this.$message.success("修改参数项成功")
            }
        },
        // 点击按钮，展示文本输入框
        showInput(row) {
            row.inputVisible = true;
            // 保持当前行展开
            if (!this.expandedRowKeys.includes(row.attr_id)) {
                this.expandedRowKeys = [...this.expandedRowKeys, row.attr_id]
            }
        },
        // 删除参数对应可选项
        handleClose(index, row) {
            row.attr_vals.splice(index, 1)
            this.saveAttrVals(row)
        },
    },
    mounted() {
        this.getparaList()  //挂载之后调用
    },
    //计算属性
    computed: {
        //按钮禁用计算属性
        isBtnDisabled() {
            if (this.selestKeys.length !== 3) {
                return true
            }
            return false
        },
        //当前选中的三级分类的id
        cateId() {
            if (this.selestKeys.length === 3) {
                return this.selestKeys[2]
            }
            return null
        },
        //计算对话框头部参数
        titleText() {
            if (this.activeName === 'many') {
                return '动态参数'
            }
            return '静态属性'
        }

    }
}
</script>
<style scoped>
.el-row {
    margin: 12px 0;
}

.el-card {
    margin-top: 12px;
}

.el-tag {
    margin-left: 12px;
}

.button-new-tag {
    margin-left: 12px;
}

.input-new-tag {
    width: 120px;
    margin-left: 12px;
}
</style>